<?php

/**
 * This is the model class for table "notification".
 *
 * The followings are the available columns in table 'notification':
 * @property integer $id
 * @property integer $user_id
 * @property string $type
 * @property string $action
 * @property string $posttime
 * @property string $content
 * @property integer $follow
 * @property integer $read
 *
 * The followings are the available model relations:
 * @property User $user
 */
class Notification extends CActiveRecord
{
	/**
	 * @return string the associated database table name
	 */
	public function tableName()
	{
		return 'notification';
	}

	/**
	 * @return array validation rules for model attributes.
	 */
	public function rules()
	{
		// NOTE: you should only define rules for those attributes that
		// will receive user inputs.
		return array(
			array('user_id, type, action, posttime, content', 'required'),
			array('user_id, follow, read', 'numerical', 'integerOnly'=>true),
			array('type, action', 'length', 'max'=>20),
			// The following rule is used by search().
			// @todo Please remove those attributes that should not be searched.
			array('id, user_id, type, action, posttime, content, follow, read', 'safe', 'on'=>'search'),
		);
	}

	/**
	 * @return array relational rules.
	 */
	public function relations()
	{
		// NOTE: you may need to adjust the relation name and the related
		// class name for the relations automatically generated below.
		return array(
			'user' => array(self::BELONGS_TO, 'User', 'user_id'),
		);
	}

	/**
	 * @return array customized attribute labels (name=>label)
	 */
	public function attributeLabels()
	{
		return array(
			'id' => 'ID',
			'user_id' => 'User',
			'type' => 'Type',
			'action' => 'Action',
			'posttime' => 'Posttime',
			'content' => 'Content',
			'follow' => 'Follow',
			'read' => 'Read',
		);
	}

	/**
	 * Retrieves a list of models based on the current search/filter conditions.
	 *
	 * Typical usecase:
	 * - Initialize the model fields with values from filter form.
	 * - Execute this method to get CActiveDataProvider instance which will filter
	 * models according to data in model fields.
	 * - Pass data provider to CGridView, CListView or any similar widget.
	 *
	 * @return CActiveDataProvider the data provider that can return the models
	 * based on the search/filter conditions.
	 */
	public function search()
	{
		// @todo Please modify the following code to remove attributes that should not be searched.

		$criteria=new CDbCriteria;

		$criteria->compare('id',$this->id);
		$criteria->compare('user_id',$this->user_id);
		$criteria->compare('type',$this->type,true);
		$criteria->compare('action',$this->action,true);
		$criteria->compare('posttime',$this->posttime,true);
		$criteria->compare('content',$this->content,true);
		$criteria->compare('follow',$this->follow);
		$criteria->compare('read',$this->read);

		return new CActiveDataProvider($this, array(
			'criteria'=>$criteria,
		));
	}

	/**
	 * Returns the static model of the specified AR class.
	 * Please note that you should have this exact method in all your CActiveRecord descendants!
	 * @param string $className active record class name.
	 * @return Notification the static model class
	 */
	public static function model($className=__CLASS__)
	{
		return parent::model($className);
	}

	/*public function add()
	{
		$this->attributes= $_POST['Notification'];
		return $this->save();
	}*/

	/*type : list, music, friend, comment +
	action:
	- list: like, comment, tag.
	- music: like, comment, tag.
	- friend: accept, deny, unfriend.
	- comment: like, tag.*/

	public function add($data)
	{
		$this->attributes = $data;
		return $this->save(false);
	}

	public function addNotification_Friend($user_id,$action,$content)
	{
		//Type: friend
		//Action:  accept, deny, unfriend.
		//Content: json user_ids
		//Follow: null
		$sql = 'INSERT INTO
					`notification`(`user_id`, `type`, `action`,`content`)
				VALUES (
					'.$user_id.',
					"friend",
					"'.$action.'",
					\''.$content.'\'
				);';
		$query=Yii::app()->db->createCommand($sql)->execute();
		return $query;
	}

	public function addNotification_News($user_id,$action,$content)
	{
		
	}



	public function updateNotificationNoRead($user_id,$type,$action,$content)
	{
		$sql = 'UPDATE
					notification
				SET
					`content`=\''.$content.'\'
				WHERE
					`user_id` = '.$user_id.' AND
					`type` = "'.$type.'" AND
					`read` = 0 AND
					`action` = "'.$action.'"';
		$query=Yii::app()->db->createCommand($sql)->execute();
		return $query;
	}

	public function viewNotificationNoRead($user_id,$type,$action)
	{
		$sql = 'SELECT
					`content`
				FROM
					notification
				WHERE
					`user_id` = '.$user_id.' AND
					`type` = "'.$type.'" AND
					`read` = 0 AND
					`action` = "'.$action.'"';
		$query = Yii::app()->db->createCommand($sql)->queryRow();
		return $query;
	}


	public function addNotification_List()
	{
		//Type: list_1
		//Action:  like, comment, tag.
		//Content: json user_ids
		//Follow: 1
	}
	public function addNotification_Music()
	{
		//Type: music_1
		//Action:  like, comment, tag.
		//Content: json user_ids
		//Follow: 1
	}
	public function addNotification_Comment()
	{
		//Type: comment_1
		//Action:  like, tag.
		//Content: json user_ids
		//Follow: 1
	}

	public function edit($fromUserId,$toUserId,$id,$type,$action)
	{
		$notifications = $this->viewDontRead($toUserId,$id,$type,$action);
		$data = json_decode($notifications['content'],true);
			if(!isset($data[$fromUserId]))
			{
				$data[$fromUserId] = 1;
				$notifications['content'] = json_encode($data);
				return $notifications->save();
			}
			else
				return false;
	}

	public function view($notification_id)
	{
		return $this->findByPk($notification_id)->attributes;
	}
	public function viewDontRead($user_id,$id,$type,$action)
	{
		$Criteria = new CDbCriteria();
		if($type != 'friend')
			$type = $type.'_'.$id;
		$Criteria->condition = "user_id = $user_id ".'AND type ="'.$type.'" AND action ="'.$action.'" AND `read` = 0';
		$data = $this->find($Criteria);
		return $data;
	}

	public function viewListNotification($user_id,$page=1)
	{
		$Criteria = new CDbCriteria();
		$Criteria->condition = "user_id = $user_id";
		$Criteria->order = 'id DESC';
		$Criteria->limit = 5;
		$Criteria->offset = ($page -1)*5;
		$data = $this->findAll($Criteria);
		return $data;
	}

	public function allRead($user_id)
	{
		$sql = 'UPDATE `notification` SET `read`=1 WHERE `user_id` = '.$user_id.' AND `read` = 0';
		$query=Yii::app()->db->createCommand($sql)->execute();
		return $query;
	}

	public function getQuantityUnread($user_id)
	{
		$sql='
			SELECT
				COUNT(`read`) As countNotification
			FROM
				notification
			WHERE
				user_id = '.$user_id.'
			AND
				`read` = 0';
		$query=Yii::app()->db->createCommand($sql)->queryRow();
		return $query;
	}
}
